//
//  RecommendViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/7.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommendTableViewCell.h"
#import "RecommmendModel.h"
#import "LibraryDetailViewController.h"

@interface RecommendViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *modelArray;

@property(nonatomic, assign)NSInteger index;

@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"推荐影片";
    self.navigationController.navigationBar.translucent = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecommendCell"];
    self.tableView.rowHeight = 110;
    
    [self getData];
    self.index = 10;
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    // 上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self loadMore];
    }];
    
    
}

// 加载更多
- (void)loadMore
{
    self.index += 10;
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/movie_traces/recommend_movie_list"];
    NSString *size = [NSString stringWithFormat:@"%ld",self.index];
    NSDictionary* URLParams = @{
                                @"page": @"1",
                                @"page_size": size,
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    
    [request addValue:@"sessionid=mvbly4g7678j33vz0114g66txroocgol" forHTTPHeaderField:@"Cookie"];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            NSDictionary *resultDic = dic[@"result"];
            NSMutableArray *dataArray = [NSMutableArray array];
            dataArray = resultDic[@"data"];
            self.modelArray = [NSMutableArray array];
            for (NSDictionary *dataDic in dataArray) {
                RecommmendModel *model = [[RecommmendModel alloc]init];
                [model setValuesForKeysWithDictionary:dataDic];
                NSMutableArray *watchArray = dataDic[@"watched_users"];
                for (NSDictionary *watchDic in watchArray) {
                    model.header = watchDic[@"header"];
                }
                NSMutableArray *tagsArray = [NSMutableArray array];
                tagsArray = dataDic[@"tags"];
                for (NSDictionary *tagsDic in tagsArray) {
                    [model setValuesForKeysWithDictionary:tagsDic];
                }
                [self.modelArray addObject:model];
            }
            dispatch_barrier_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            });
            
        }
        else
        {
            // Failure
            NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
        }
    }];
    [task resume];

}

// 请求数据
- (void)getData
{
       NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/movie_traces/recommend_movie_list"];
    NSDictionary* URLParams = @{
                                @"page": @"1",
                                @"page_size": @"10",
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    [request addValue:@"sessionid=mvbly4g7678j33vz0114g66txroocgol" forHTTPHeaderField:@"Cookie"];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *resultDic = dic[@"result"];
            NSMutableArray *dataArray = [NSMutableArray array];
            dataArray = resultDic[@"data"];
            self.modelArray = [NSMutableArray array];
            for (NSDictionary *dataDic in dataArray) {
                RecommmendModel *model = [[RecommmendModel alloc]init];
                [model setValuesForKeysWithDictionary:dataDic];
                NSMutableArray *watchArray = dataDic[@"watched_users"];
                for (NSDictionary *watchDic in watchArray) {
                    model.header = watchDic[@"header"];
                }
                NSMutableArray *tagsArray = [NSMutableArray array];
                tagsArray = dataDic[@"tags"];
                for (NSDictionary *tagsDic in tagsArray) {
                    [model setValuesForKeysWithDictionary:tagsDic];
                }
                [self.modelArray addObject:model];
            }
            dispatch_barrier_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
            });
            
           }
        else
        {
            // Failure
        }
    }];
    [task resume];
}

static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
                          [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]],
                          [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]
                          ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
                           [URL absoluteString],
                           NSStringFromQueryParameters(queryParameters)
                           ];
    return [NSURL URLWithString:URLString];
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendCell" forIndexPath:indexPath];
    RecommmendModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark --- 点击cell事件 ---
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommmendModel *model = self.modelArray[indexPath.row];
    LibraryDetailViewController *libraryDetailVC = [[LibraryDetailViewController alloc]init];
    libraryDetailVC.movieId = model.movieId;
    [self.navigationController pushViewController:libraryDetailVC animated:YES];
}


























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
